import React, { useEffect, useState } from 'react'
import styles from './index.module.css'
import http from '../../utils/http'
import { ProductCard } from 'react-vant';
import { InfiniteScroll, List, SearchBar } from 'antd-mobile'
import NavBars from '../../components/NavBars';
import { useDispatch } from 'react-redux'
import { setDataStrote } from '../../store/DataSlice'
import { useNavigate } from 'react-router-dom';
function Index() {
  const navigate = useNavigate()
  const dispatch = useDispatch()
  const [list, setList] = useState([])
  const [search, setSearch] = useState([])
  const [value, setValue] = useState('')
  const [page, setPage] = useState(1)
  const [hasMore, setHasMore] = useState(true)
  const getList = async () => {
    const res = await http.get('/api/list', {
      params: {
        page
      }
    })

    console.log(res);

    const { code, data } = res.data

    if (code === 200) {
      setList([...list, ...data])
      setPage((prev) => prev + 1)
      dispatch(setDataStrote({ data: data }))
    }

    if (data.length === 0) {
      setHasMore(false)
    }

  }

  useEffect(() => {
    getList()
  }, [])

  const handleDetail = (id) => {
    navigate(`/detail/${id}`)
  }

  const handleSearch = async (val) => {
    setValue(val)
    if (val !== '') {
      const res = await http.get('/api/list', {
        params: {
          wd: val
        }
      })

      console.log(res);

      const { code, data } = res.data

      if (code === 200) {
        setSearch(data)
      }
    }
    else {
      setSearch([])
    }
  }
  return (
    <div>
      <NavBars title='首页'></NavBars>
      <div>
        <SearchBar
          value={value}
          onChange={handleSearch}
          placeholder='请输入搜索内容'
        />
        <div className={styles.search_wroe}>
          {
            search?.map((item, ind) => (
              <ProductCard
                key={ind}
                num={item.date}
                price={item.price}
                desc={item.title}
                title={item.id}
                thumb={item.image}
              />
            ))
          }
        </div>
      </div>
      <div>
        <List>
          {
            list?.map((item, ind) => (
              <List.Item key={ind} onClick={() => handleDetail(item.id)}>
                <ProductCard
                  num={item.date}
                  price={item.price}
                  desc={item.title}
                  title={item.id}
                  thumb={item.image}
                />
              </List.Item>
            ))
          }
        </List>

        <InfiniteScroll loadMore={getList} hasMore={hasMore} />
      </div>
    </div>
  )
}

export default Index
